package com.yuyou.tas.lesson.controller;

import com.yuyou.tas.lesson.service.ILessonMaterialService;
import com.yuyou.tas.lesson.service.ILessonService;
import com.yuyou.tas.lesson.service.comm.OrganLimitService;
import com.yuyou.tas.service.api.lesson.dto.DtoLessonMaterial;
import com.yuyou.tas.service.api.lesson.dto.DtoLessonMaterialWithName;
import com.yuyou.tas.service.api.lesson.entity.Lesson;
import com.yuyou.tas.util.bean.*;
import com.yuyou.tas.util.enums.OrganLimitEnums;
import com.yuyou.tas.util.enums.lesson.LessonEnums;
import com.yuyou.tas.util.exception.BusinessException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.ArrayUtils;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(value = "LessonMaterialController", description = "课程素材操作接口")
@Validated
@RestController
@RequestMapping(value = "/api/LessonMaterial")
public class LessonMaterialController extends BaseController {

	@Autowired
	private ILessonMaterialService service;

	@Autowired
	private OrganLimitService organLimitService;

	@Autowired
	private ILessonService lessonService;

	@ApiOperation(value = "添加素材")
	@RequestMapping(value = "/addLessonMaterial", method = RequestMethod.POST)
	public ReturnResult addLessonMaterial(
			HttpServletRequest request,
			@Validated @ApiParam(value = "课程ID") @NotNull(message = "课程ID不能为空") @RequestParam(value = "lessonId") Long lessonId,
			@Validated @ApiParam(value = "素材ID,多个用逗号隔开") @NotEmpty(message = "素材ID不能为空") @RequestParam(value = "baseMaterialIds") String[] baseMaterialIds) throws Exception {

		List<DtoLessonMaterialWithName> list = service.findLeMatNameByLessonId(lessonId);//获取该课程已有素材
		if(!CollectionUtils.isEmpty(list)){
			List<String> repeatsList =
				list.stream().filter(lm -> ArrayUtils.contains(baseMaterialIds , String.valueOf(lm.getBaseMaterialId()))).map(DtoLessonMaterialWithName::getName).collect(Collectors.toList());
			if(!CollectionUtils.isEmpty(repeatsList)){//素材有重复引用
				throw new BusinessException("你选择的辅助素材已经存在: [ " + String.join(",",repeatsList)+" ]");
			}
		}

		LoginRedisObj user = this.getUserObj(request);
		ResBoolSimpleInfo info = service.addLessonMaterial(lessonId,
				baseMaterialIds, user.getIsSystem() ? 1 : 0, null, user,
				user.getOrganizationId());
		return ReturnResult
				.returnRes(info.isSuccess(), info.getMessage(), null);
	}

	@ApiOperation(value = "删除素材库素材")
	@RequestMapping(value = "/delLessonMaterial", method = RequestMethod.POST)
	public ReturnResult delLessonMaterial(
			@Validated @NotNull(message = "ID不能为空") @ApiParam(value = "课程素材关联ID", required = true) @RequestParam(value = "id") Long id,
			HttpServletRequest request) throws Exception {
		LoginRedisObj user = this.getUserObj(request);
		if (!user.getIsSystem()) {
			organLimitService.checkOrganByOrganId(user.getOrganizationId(), id,
					OrganLimitEnums.type.lesson_material);
		}
		ResBoolSimpleInfo info = service.delLessonMaterial(id);
		return ReturnResult
				.returnRes(info.isSuccess(), info.getMessage(), null);
	}

	@ApiOperation(value = "分页查询课程素材")
	@RequestMapping(value = "/findLessonMaterial", method = {
			RequestMethod.GET, RequestMethod.POST })
	public ReturnResult<DtoLessonMaterial> findLessonMaterial(
			HttpServletRequest request,
			@Validated @ModelAttribute PageParams pageParams,
			@Validated @NotNull @ApiParam(value = "课程ID") @RequestParam(value = "lessonId") Long lessonId) {
		Map<String, Object> conditions = new HashMap<>();
		Pagination<DtoLessonMaterial> queryPgn = new Pagination<>();

		LoginRedisObj user = this.getUserObj(request);
		Lesson lesson = lessonService.selectByPrimaryKey(lessonId);

		//校验该机构对系统课程的年级科目权限
		if(lesson != null && LessonEnums.type.standard.getValue() == lesson.getType() && !user.getIsSystem()
				&&(user.getOrganSubSecMap() == null
				|| !user.getOrganSubSecMap().containsKey(lesson.getDataSubject())
				|| CollectionUtils.isEmpty(user.getOrganSubSecMap().get(lesson.getDataSubject()))
				|| !user.getOrganSubSecMap().get(lesson.getDataSubject()).contains(lesson.getBaseSectionId()))){

			queryPgn = Pagination.getZeroPage(pageParams);

		}else {
			conditions.put("lessonId", lessonId);
			conditions.put("organ_id", user.getOrganizationId());// 默认查询个人所在机构的校区

			queryPgn.setConditions(conditions);
			queryPgn.setPageParams(pageParams);

			int total = service.findLessonMaterialCount(queryPgn);
			queryPgn.setTotal(total);
			queryPgn.toBePage();
			if (total > 0) {
				List<DtoLessonMaterial> list = service
						.findLessonMaterialPageList(queryPgn);
				queryPgn.setList(list);
			}
		}

		HashMap<String, Object> ext = new HashMap<String, Object>() {
			private static final long serialVersionUID = -4869119469706565626L;

			{
				put("name", lesson.getName());
				put("status", lesson.getStatus());
				put("dataSubject", lesson.getDataSubject());
			}
		};
		queryPgn.setExt(ext);
		return ReturnResult.success(queryPgn);
	}

}
